import os
import time
from datetime import datetime

from model.models import db, TSysNovelChapter, TSysFile

from base import baidu_aipspeech
from base import oss_client
from moviepy.editor import CompositeAudioClip
from moviepy.audio.io.AudioFileClip import AudioFileClip
from moviepy.editor import afx
from moviepy.editor import concatenate_audioclips

audio_temp_path = "../audio_temp"
type_MP3="mp3"

def create_audio_from_text(text,chapter_id):
    if not os.path.exists(audio_temp_path):
        os.makedirs(audio_temp_path)

    audio_temp_file=audio_temp_path + os.sep + str(chapter_id) + "_temp" + ".mp3"
    baidu_aipspeech.get_audio_from_text(text=text, file_name=audio_temp_file)

    mixed_audio_file = audio_temp_path + os.sep + str(chapter_id) + ".mp3"
    mix_bgm_and_audios(audio_path=audio_temp_file, out_path=mixed_audio_file)
    upload_mixed_audio(chapter_id=chapter_id, dest_audio_file=mixed_audio_file)
    return {"success": True, "value": {"mixed_audio_file_path":mixed_audio_file, "audio_temp_file_path":audio_temp_file}, "msg": "音频素材创建完毕"}

def create_short_audio_from_text(text_list,chapter_id):
    audio_temp_short_audios_path = audio_temp_path + os.sep + str(chapter_id)
    temp_short_audios=[]
    subtiles=[]

    if not os.path.exists(audio_temp_path):
        os.makedirs(audio_temp_path)
    if not os.path.exists(audio_temp_short_audios_path):
        os.makedirs(audio_temp_short_audios_path)

    short_audio_no=0
    for text in text_list:
        if len(text)>= 60:
            print('字幕长度: ' + str(len(text)))

        short_audio_temp_file = audio_temp_short_audios_path + os.sep +  str(short_audio_no) + ".mp3"
        baidu_aipspeech.get_audio_from_short_text(text=text, file_name=short_audio_temp_file)
        short_audio_no += 1
        temp_short_audio=AudioFileClip(short_audio_temp_file)
        if temp_short_audio is not None:
            subtiles.append({'subtile' : text, 'duration' : temp_short_audio.duration})
            temp_short_audios.append(temp_short_audio.subclip(0, temp_short_audio.duration))

    concatenated_audio = concatenate_audioclips(temp_short_audios)
    mixed_audio_file = audio_temp_path + os.sep + str(chapter_id) + ".mp3"
    mix_bgm_and_audios_fileclip(audio=concatenated_audio, out_path=mixed_audio_file)
    upload_mixed_audio(chapter_id=chapter_id, dest_audio_file=mixed_audio_file)
    return {"success": True, "value": {"mixed_audio_file_path":mixed_audio_file, "audio_temp_path":audio_temp_short_audios_path, "subtiles":subtiles}, "msg": "音频素材创建完毕"}


def mix_bgm_and_audios_fileclip(audio, out_path):
    bgm1 = AudioFileClip("bgms/bgm2.mp3")
    bgm1 = bgm1.volumex([0.1, 0.1])

    audio = audio.volumex([0.8, 0.8])

    bgm1 = afx.audio_loop(bgm1, duration=audio.duration)
    mixed_audio = CompositeAudioClip([bgm1,audio])
    mixed_audio = mixed_audio.volumex([0.6, 0.6])
    mixed_audio.write_audiofile(filename=out_path, fps=44100)

#合成讲解和背景音乐
def mix_bgm_and_audios(audio_path, out_path):
    bgm1 = AudioFileClip("bgms/bgm1.mp3")
    bgm1 = bgm1.volumex([0.1, 0.1])

    audio = AudioFileClip(audio_path)
    audio = audio.volumex([0.8, 0.8])

    bgm1 = afx.audio_loop(bgm1, duration=audio.duration)
    mixed_audio = CompositeAudioClip([bgm1,audio])
    mixed_audio = mixed_audio.volumex([0.6, 0.6])
    mixed_audio.write_audiofile(filename=out_path, fps=44100)

def upload_mixed_audio(dest_audio_file, chapter_id):
    # 上传音频
    chapter = TSysNovelChapter.query.filter_by(id=chapter_id).first()
    if chapter is not None:
        file_name = str(chapter_id) + "-" + str(time.time()) + ".mp3"
        bucket_name = "audios" + "-" + str(chapter.user_id) + "-" + str(chapter_id)
        oss_client.upload_file(file_path=dest_audio_file, file_name=file_name, bucket_name=bucket_name)
        tSysFile = TSysFile(
            user_id=chapter.user_id,
            correlation_id=chapter.novel_id,
            correlation_type='novel',
            correlation_sub_id=chapter_id,
            name=chapter.title,
            local_path=file_name,
            remote_path=bucket_name,
            file_type=type_MP3,
            create_date=datetime.now(),
            update_date=datetime.now()
        )
        db.session.add(tSysFile)
        db.session.commit()

